package com.example.wechat.login.controller;

import com.alibaba.fastjson.JSON;
import com.example.wechat.login.dto.ApiResponse;
import com.example.wechat.login.entity.SpeechRecognitionHistory;
import com.example.wechat.login.enums.SpeechStatusEnum;
import com.example.wechat.login.service.SpeechRecognitionHistoryService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 腾讯云 ASR 回调接口
 */
@RestController
@RequestMapping("/api/asr/callback")
@Slf4j
public class AsrCallbackController {

    @Resource
    private SpeechRecognitionHistoryService speechRecognitionHistoryService;

    @PostMapping("/recognition")
    @Transactional
    public ApiResponse<Void> handleRecognitionCallback(AsrCallbackRequest request) {
        log.info("handleRecognitionCallback: {}", JSON.toJSONString(request));
        // 查询任务是否存在
        SpeechRecognitionHistory task = speechRecognitionHistoryService.findByTaskId(request.getRequestId());
        if (task == null) {
            throw new RuntimeException("请求id不存在: " + request.getRequestId());
        }
        // 更新任务状态和识别结果
        if(request.getCode() == 0){
            task.setStatus(SpeechStatusEnum.COMPLETED.getCode());
            task.setRecognitionResult(request.getText());
            task.setAudioTime(BigDecimal.valueOf(request.getAudioTime()));
        }else {
            task.setStatus(SpeechStatusEnum.FAILURE.getCode());
            task.setMessage(request.getMessage());

        }
        task.setAudioUrl(request.getAudioUrl());
        task.setResultDetail(request.getResultDetail());
        speechRecognitionHistoryService.update(task);
        return ApiResponse.success() ;
    }

    /**
     * 腾讯云 ASR 回调请求体
     */
    @Data
    public static class AsrCallbackRequest {
        private Integer code;
        private String message;
        private String requestId;
        private String appid;
        private String projectid;
        private String audioUrl;
        private String text;
        private String resultDetail;
        private double audioTime;

    }


}